import { useCallback } from "react";
import { useSelector, useDispatch } from "react-redux"

import { useAssType } from "./ass_type";

import Creators from "../store/actions"
// 拿到抢购的api
import seckillApi from "../api/seckill"


export const useSeckill = () => {
  const seckills = useSelector(state => state.seckill_list)
  const { curPage, eachPage, rows, total, maxPage } = seckills

  // 类型 状态
  const [{
    ChildAll,
    TotalAl,
    assType
  }, { getassType, addAssTypeToReducer }] = useAssType()

  const dispatch = useDispatch()

  // 发送请求获取数据
  const getSeckills = useCallback(
    async () => {
      const data = await seckillApi.get({ curPage, eachPage })
      dispatch(Creators.seckillGetSeckill({ data }))

      await getassType()

    }, [curPage, eachPage])
  // 下架商品
  const offState = async (_id) => {
    const result = await seckillApi.changeState({ _id, State: "0" })
    getSeckills()
    return result.ok
  }
  // 上架商品
  const onState = async (_id) => {
    const result = await seckillApi.changeState({ _id, State: "1" })
    getSeckills()
    return result.ok
  }

  // 修改页码
  const choseCurpage = (setcurpage) => {
    console.log("修改当前页");

    dispatch(Creators.seckillSetlistCurpage({ setcurpage }))
  }

  // 修改每页显示条数
  const choseEachpage = (seteachpage) => {

    dispatch(Creators.seckillSetlistEachpage({ seteachpage }))
  }
  // 查询数据
  const selectSeckill = async (info) => {
    const data = await seckillApi.selectSeckills({ ...info })

    dispatch(Creators.seckillGetSeckill({ data }))
    return data.rows
  }
  // 通过父类型查询数据
  const selectFromToType = async (info) => {
    const data = {}
    data.rows = await seckillApi.selectFromToType(info)
    dispatch(Creators.seckillGetSeckill({ data }))
    return data.rows
  }
  // 通过子类型查询活动数据
  const selectFromchildType= async (info) => {
    const data = {}
    data.rows = await seckillApi.selectFromchildType(info)
    dispatch(Creators.seckillGetSeckill({ data }))
    return data.rows
  }

  // 删除活动
  const deleteSeckill= async (info) => {
   const result = await seckillApi.deleteSeckill(info)
   const data = await seckillApi.get({ curPage, eachPage })
   dispatch(Creators.seckillGetSeckill({ data }))
    return result
  }

  return [{
    rows, curPage, eachPage, total, maxPage, ChildAll,
    TotalAl,
    assType
  }, { getSeckills, onState, offState, choseCurpage, choseEachpage, selectSeckill,deleteSeckill,
    selectFromToType,selectFromchildType }]

}